package org.star.exception;

import com.alibaba.csp.sentinel.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.star.enums.ResponseEnum;
import org.star.result.R;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author liuhaibo
 * @Description
 * @Date 2023/5/30 15:53
 * @RestControllerAdvice： 在controller层添加通知。如果使用@ControllerAdvice，则方法上需要添加@ResponseBody
 */
@Slf4j
@Component
@RestControllerAdvice(basePackages = "org.star.controller")
public class GlobalExceptionHandler {
    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> errorMap = new HashMap<>(2);
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(ResponseEnum.PARAMETER_VALIDATE_FAILED_ERROR.getCode(), ResponseEnum.PARAMETER_VALIDATE_FAILED_ERROR.getMessage()).data(errorMap);
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public R handleBusinessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return R.error().code(ResponseEnum.BUSINESS_ERROR.getCode()).message(e.getMessage());
    }

    /**
     * 处理其他异常
     * 坑：使用全局异常处理器时，如果不加Tracer.trace(e);，将会导致Sentinel中异常无法被捕获！
     * 参考：https://blog.csdn.net/a309220728/article/details/131302645
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleOtherException(Throwable e) {
        Tracer.trace(e);
        return R.error(ResponseEnum.SERVER_INTERNAL_ERROR.getCode(), ResponseEnum.SERVER_INTERNAL_ERROR.getMessage());
    }
}
